<template>
  <div class="app-container">
    <!-- 命令执行区域 -->
    <el-card class="command-card mb-4" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>批量命令执行</span>
          <el-tag type="success" size="small">已选择 {{ selectedHosts.length }} 台服务器</el-tag>
        </div>
      </template>
      <el-form label-width="80px">
        <el-form-item label="执行命令">
          <el-input
            v-model="commandText"
            type="textarea"
            :rows="3"
            placeholder="请输入要执行的命令，如: ls -la&#10;或输入多行命令：&#10;cd /home/project&#10;ls -la&#10;ps aux | grep python"
            clearable
            style="width: 100%; font-family: monospace;"
            show-word-limit
            maxlength="2000"
          />
        </el-form-item>
        <el-form-item label-width="80px">
          <el-space>
            <el-button
              type="primary"
              :icon="Connection"
              @click="handleExecuteCommand"
              :disabled="selectedHosts.length === 0 || !commandText"
              :loading="commandExecuting"
              size="default"
            >
              执行命令
            </el-button>
            <el-button
              type="success"
              :icon="CaretRight"
              @click="handleBatchControlAgent('start')"
              :disabled="selectedHosts.length === 0"
              size="default"
            >
              启动Agent
            </el-button>
            <el-button
              type="warning"
              :icon="RefreshRight"
              @click="handleBatchControlAgent('restart')"
              :disabled="selectedHosts.length === 0"
              size="default"
            >
              重启Agent
            </el-button>
            <el-button
              type="danger"
              :icon="SwitchButton"
              @click="handleBatchControlAgent('stop')"
              :disabled="selectedHosts.length === 0"
              size="default"
            >
              停止Agent
            </el-button>
          </el-space>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="主机名称" prop="host_name">
        <el-input
          v-model="queryParams.host_name"
          placeholder="请输入主机名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="主机IP" prop="host_ip">
        <el-input
          v-model="queryParams.host_ip"
          placeholder="请输入主机IP"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="连接状态" prop="connection_status">
        <el-select v-model="queryParams.connection_status" placeholder="请选择" clearable style="width: 120px">
          <el-option label="已连接" value="connected" />
          <el-option label="未连接" value="disconnected" />
          <el-option label="连接错误" value="error" />
        </el-select>
      </el-form-item>
      <el-form-item label="Agent状态" prop="agent_status">
        <el-select v-model="queryParams.agent_status" placeholder="请选择" clearable style="width: 120px">
          <el-option label="运行中" value="running" />
          <el-option label="已停止" value="stopped" />
          <el-option label="未知" value="unknown" />
          <el-option label="错误" value="error" />
        </el-select>
      </el-form-item>
      <el-form-item label="部署状态" prop="deploy_status">
        <el-select v-model="queryParams.deploy_status" placeholder="请选择" clearable style="width: 120px">
          <el-option label="已部署" value="deployed" />
          <el-option label="部署中" value="deploying" />
          <el-option label="未部署" value="not_deployed" />
          <el-option label="部署失败" value="deploy_failed" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb-2">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :icon="Plus"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          :icon="Upload"
          @click="handleImport"
        >批量导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          :icon="Upload"
          @click="handleBatchDeploy"
          :disabled="selectedHosts.length === 0"
        >批量部署Agent</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          :icon="Connection"
          @click="handleBatchTestConnection"
          :disabled="selectedHosts.length === 0"
          :loading="batchTestLoading"
        >批量测试连接</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :icon="CircleCheck"
          @click="handleBatchGetStatus"
          :disabled="selectedHosts.length === 0"
        >一键获取状态</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          :icon="Key"
          @click="handleBatchInitRoot"
          :disabled="selectedHosts.length === 0 || selectedHosts.every(h => h.ssh_username === 'root')"
        >批量切换root</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          :icon="Delete"
          @click="handleBatchDelete"
          :disabled="selectedHosts.length === 0"
        >批量删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 主机列表表格 -->
    <el-table
      v-loading="loading"
      :data="hostList"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主机名称" align="center" prop="host_name" min-width="150" sortable :sort-method="naturalSortByHostName" />
      <el-table-column label="主机IP" align="center" prop="host_ip" width="140" sortable />
      <el-table-column label="内网IP" align="center" width="140" sortable prop="internal_ip">
        <template #default="{ row }">
          <span v-if="row.internal_ip" style="color: #67C23A;">{{ row.internal_ip }}</span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="SSH端口" align="center" prop="ssh_port" width="80" sortable />
      <el-table-column label="SSH用户名" align="center" width="120" sortable prop="ssh_username">
        <template #default="{ row }">
          <el-tag v-if="row.ssh_username === 'root'" type="success">{{ row.ssh_username }}</el-tag>
          <el-tag v-else type="warning">{{ row.ssh_username }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="Agent路径" align="center" prop="agent_path" min-width="180" show-overflow-tooltip sortable />
      <el-table-column label="连接状态" align="center" width="100" sortable prop="connection_status">
        <template #default="{ row }">
          <el-tag v-if="row.connection_status === 'connected'" type="success">已连接</el-tag>
          <el-tag v-else-if="row.connection_status === 'error'" type="danger">连接错误</el-tag>
          <el-tag v-else type="warning">未连接</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="延迟" align="center" width="140" sortable prop="latency">
        <template #default="{ row }">
          <span v-if="row.latency !== undefined && row.latency !== null">
            <el-tag v-if="row.latency < 100" type="success">
              {{ row.latency }}ms
              <span v-if="row.connection_type" style="margin-left: 4px;">
                {{ row.connection_type === '内网' ? '🏠' : '🌐' }}
              </span>
            </el-tag>
            <el-tag v-else-if="row.latency < 300" type="warning">
              {{ row.latency }}ms
              <span v-if="row.connection_type" style="margin-left: 4px;">
                {{ row.connection_type === '内网' ? '🏠' : '🌐' }}
              </span>
            </el-tag>
            <el-tag v-else type="danger">
              {{ row.latency }}ms
              <span v-if="row.connection_type" style="margin-left: 4px;">
                {{ row.connection_type === '内网' ? '🏠' : '🌐' }}
              </span>
            </el-tag>
          </span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="Agent状态" align="center" width="100" sortable prop="agent_status">
        <template #default="{ row }">
          <el-tag v-if="row.agent_status === 'running'" type="success">运行中</el-tag>
          <el-tag v-else-if="row.agent_status === 'stopped'" type="warning">已停止</el-tag>
          <el-tag v-else-if="row.agent_status === 'error'" type="danger">错误</el-tag>
          <el-tag v-else type="warning">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="部署状态" align="center" width="110" sortable prop="deploy_status">
        <template #default="{ row }">
          <el-tooltip v-if="row.deploy_status === 'deploy_failed' && row.deploy_error" :content="row.deploy_error" placement="top">
            <el-tag type="danger">部署失败</el-tag>
          </el-tooltip>
          <el-tag v-else-if="row.deploy_status === 'deployed'" type="success">已部署</el-tag>
          <el-tag v-else-if="row.deploy_status === 'deploying'" type="warning">
            <el-icon class="is-loading"><Loading /></el-icon> 部署中
          </el-tag>
          <el-tag v-else type="info">未部署</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="Agent版本" align="center" prop="agent_version" width="100" sortable />
      <el-table-column label="最后连接时间" align="center" prop="last_connect_time" width="160" sortable />
      <el-table-column label="操作" align="center" width="220" fixed="right">
        <template #default="{ row }">
          <el-button
            link
            type="primary"
            :icon="Edit"
            size="small"
            @click="handleUpdate(row)"
          >编辑</el-button>
          <el-button
            link
            type="danger"
            :icon="Delete"
            size="small"
            @click="handleDelete(row)"
          >删除</el-button>
          <el-dropdown trigger="click" @command="(cmd) => handleDropdownCommand(cmd, row)">
            <el-button link type="primary" size="small">
              更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item :icon="Connection" command="testConnection">测试连接</el-dropdown-item>
                <el-dropdown-item 
                  v-if="row.ssh_username !== 'root'"
                  :icon="Key" 
                  command="initRoot"
                >切换root</el-dropdown-item>
                <el-dropdown-item :icon="Document" command="viewLog">查看日志</el-dropdown-item>
                <el-dropdown-item divided :disabled="row.deploy_status !== 'deployed'">Agent服务</el-dropdown-item>
                <el-dropdown-item 
                  :icon="CaretRight" 
                  command="start"
                  :disabled="row.deploy_status !== 'deployed'"
                >启动</el-dropdown-item>
                <el-dropdown-item 
                  :icon="RefreshRight" 
                  command="restart"
                  :disabled="row.deploy_status !== 'deployed'"
                >重启</el-dropdown-item>
                <el-dropdown-item 
                  :icon="SwitchButton" 
                  command="stop"
                  :disabled="row.deploy_status !== 'deployed'"
                >停止</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.page_num"
      v-model:limit="queryParams.page_size"
      @pagination="getList"
    />

    <!-- 添加/编辑主机对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="主机名称" prop="host_name">
          <el-input v-model="form.host_name" placeholder="请输入主机名称" />
        </el-form-item>
        <el-form-item label="主机IP" prop="host_ip">
          <el-input v-model="form.host_ip" placeholder="请输入主机IP地址" />
        </el-form-item>
        <el-form-item label="SSH端口" prop="ssh_port">
          <el-input-number v-model="form.ssh_port" :min="1" :max="65535" />
        </el-form-item>
        <el-form-item label="SSH用户名" prop="ssh_username">
          <el-input v-model="form.ssh_username" placeholder="请输入SSH用户名" />
        </el-form-item>
        <el-form-item label="SSH密码" prop="ssh_password">
          <el-input
            v-model="form.ssh_password"
            type="password"
            placeholder="请输入SSH密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="Agent路径" prop="agent_path">
          <el-input v-model="form.agent_path" placeholder="Agent项目路径，如：/home/project/" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog
      title="批量导入主机"
      v-model="importDialogVisible"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-alert type="success" :closable="false" class="mb-3">
        <p>批量导入主机，适用于多台服务器使用相同的SSH账号密码的情况</p>
        <p>可以手动输入IP列表（每行一个），或者上传包含IP列表的文本文件</p>
      </el-alert>
      <el-alert type="warning" :closable="false" class="mb-3" v-if="importForm.auto_init_root">
        <p><strong>自动初始化root账号功能说明：</strong></p>
        <p>• 系统将使用您填写的账号（如ubuntu）登录服务器</p>
        <p>• 自动执行命令将root密码设置为与当前账号相同</p>
        <p>• 测试root账号登录是否成功</p>
        <p>• 自动将SSH登录账号切换为root</p>
        <p>• 适用于ubuntu等有sudo权限且无需密码的账号</p>
      </el-alert>
      <el-form ref="importFormRef" :model="importForm" :rules="importRules" label-width="120px">
        <el-form-item label="IP地址列表" prop="ip_list_text">
          <el-input
            v-model="importForm.ip_list_text"
            type="textarea"
            :rows="8"
            placeholder="请输入IP地址，每行一个&#10;例如：&#10;192.168.1.100&#10;192.168.1.101&#10;192.168.1.102"
          />
          <div style="margin-top: 10px;">
            <el-upload
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleFileChange"
              accept=".txt"
            >
              <el-button size="small" :icon="Upload">从文件导入</el-button>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="主机名前缀" prop="name_prefix">
          <el-input v-model="importForm.name_prefix" placeholder="例如：Server，生成Server-1, Server-2..." />
        </el-form-item>
        <el-form-item label="SSH端口" prop="ssh_port">
          <el-input-number v-model="importForm.ssh_port" :min="1" :max="65535" />
        </el-form-item>
        <el-form-item label="SSH用户名" prop="ssh_username">
          <el-input v-model="importForm.ssh_username" placeholder="请输入SSH用户名" />
        </el-form-item>
        <el-form-item label="SSH密码" prop="ssh_password">
          <el-input
            v-model="importForm.ssh_password"
            type="password"
            placeholder="请输入SSH密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="Agent路径" prop="agent_path">
          <el-input v-model="importForm.agent_path" placeholder="Agent项目路径，如：/home/project/" />
        </el-form-item>
        <el-form-item label="自动切换root">
          <el-switch
            v-model="importForm.auto_init_root"
            active-text="启用（推荐ubuntu账号使用）"
            inactive-text="不启用"
          />
          <div style="color: #909399; font-size: 12px; margin-top: 5px;">
            启用后，系统将自动设置root密码并切换到root账号登录（需要sudo权限）
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitImport">确定导入</el-button>
      </template>
    </el-dialog>

    <!-- 批量部署Agent对话框 -->
    <el-dialog
      title="批量部署Agent"
      v-model="deployDialogVisible"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-alert type="info" :closable="false" class="mb-3">
        <p><strong>📦 新方案：</strong>上传Agent安装包到控制端，系统自动分发到各Agent服务器</p>
        <p style="margin-top: 8px; color: #909399; font-size: 13px;">
          ✅ 更快（并发下载） | ✅ 更安全（IP白名单+Token认证） | ✅ 更简单（一键上传）
        </p>
      </el-alert>
      
      <el-form ref="deployFormRef" :model="deployForm" :rules="deployRules" label-width="140px">
        <!-- 文件上传区域 -->
        <el-form-item label="Agent安装包" prop="agent_file_path">
          <div style="width: 100%;">
            <!-- 方式1: 上传文件（推荐） -->
            <el-upload
              ref="uploadRef"
              class="upload-demo"
              action="#"
              :http-request="handleUploadAgent"
              :show-file-list="true"
              :limit="1"
              accept=".tar.gz"
              :before-upload="beforeUploadAgent"
              :on-exceed="handleExceed"
              :file-list="uploadFileList"
              :disabled="uploadLoading"
            >
              <el-button type="primary" :icon="Upload" :loading="uploadLoading">
                {{ uploadLoading ? '上传中...' : '选择Agent文件（.tar.gz）' }}
              </el-button>
              <template #tip>
                <div class="el-upload__tip" style="margin-top: 8px;">
                  <div style="color: #67C23A; font-size: 13px; margin-bottom: 4px;">
                    📋 推荐：点击按钮选择 agent.tar.gz 文件上传
                  </div>
                  <div style="color: #909399; font-size: 12px;">
                    支持最大 500MB 的 .tar.gz 文件
                  </div>
                </div>
              </template>
            </el-upload>
            
            <!-- 上传进度条 -->
            <el-progress 
              v-if="uploadProgress > 0 && uploadProgress < 100" 
              :percentage="uploadProgress" 
              :stroke-width="8"
              style="margin-top: 12px;"
            />
            
            <!-- 分割线 -->
            <el-divider style="margin: 20px 0;">或</el-divider>
            
            <!-- 方式2: 手动输入URL/路径（兼容旧方式） -->
          <el-input
            v-model="deployForm.agent_file_path"
              placeholder="手动输入：下载URL 或 服务器本地路径（如 /tmp/agent.tar.gz）"
              clearable
            >
              <template #prefix>
                <el-icon><Document /></el-icon>
              </template>
            </el-input>
            <div style="color: #909399; font-size: 12px; margin-top: 6px;">
              💡 提示：支持 HTTP下载URL 或 服务器本地路径
            </div>
          </div>
        </el-form-item>
        
        <!-- 部署主机列表 -->
        <el-form-item label="部署到的主机">
          <div style="max-height: 150px; overflow-y: auto; width: 100%;">
            <el-tag 
              v-for="host in selectedHosts" 
              :key="host.id" 
              class="mr-2 mb-2"
              type="success"
            >
            {{ host.host_name }} ({{ host.host_ip }})
          </el-tag>
          </div>
          <div style="color: #909399; font-size: 13px; margin-top: 8px;">
            共选择 <strong style="color: #409EFF;">{{ selectedHosts.length }}</strong> 台服务器
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="handleCancelDeploy">取消</el-button>
        <el-button 
          type="primary" 
          @click="submitDeploy" 
          :loading="deployLoading"
          :disabled="!deployForm.agent_file_path || uploadLoading"
        >
          <el-icon v-if="!deployLoading"><CaretRight /></el-icon>
          {{ deployLoading ? '部署中...' : '开始部署' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 命令执行结果对话框 -->
    <el-dialog
      title="命令执行结果"
      v-model="resultDialogVisible"
      width="900px"
    >
      <el-table :data="commandResults" border>
        <el-table-column label="主机名称" align="center" prop="host_name" width="150" />
        <el-table-column label="主机IP" align="center" prop="host_ip" width="140" />
        <el-table-column label="状态" align="center" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.status === 'success'" type="success">成功</el-tag>
            <el-tag v-else type="danger">失败</el-tag>
            <!-- 显示解析出的服务状态 -->
            <div v-if="row.status === 'success' && row.result" style="margin-top: 4px; font-size: 12px;">
              <el-tag 
                v-if="row.result.toLowerCase().includes('active (running)')" 
                type="success" 
                size="small"
              >服务状态: 运行中</el-tag>
              <el-tag 
                v-else-if="row.result.toLowerCase().includes('inactive (dead)') || row.result.toLowerCase().includes('stopped')" 
                type="warning" 
                size="small"
              >服务状态: 已停止</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="耗时(ms)" align="center" prop="duration" width="100" />
        <el-table-column label="执行结果/错误信息" align="center" min-width="300">
          <template #default="{ row }">
            <el-input
              v-if="row.result || row.error"
              type="textarea"
              :value="row.result || row.error"
              readonly
              :rows="3"
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div style="text-align: left; margin-bottom: 12px; color: #909399; font-size: 12px;">
          <el-icon><InfoFilled /></el-icon>
          <span style="margin-left: 4px;">提示：服务状态已自动更新到列表的"Agent状态"列，请刷新页面查看</span>
        </div>
        <el-button type="primary" @click="resultDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 导入结果对话框 -->
    <el-dialog
      title="导入结果"
      v-model="importResultDialogVisible"
      width="900px"
      :close-on-click-modal="false"
    >
      <div v-if="importResultData">
        <!-- 统计摘要 -->
        <el-row :gutter="20" class="mb-4">
          <el-col :span="8">
            <el-statistic title="成功" :value="importResultData.success_count">
              <template #suffix>
                <span style="font-size: 14px; color: #909399;">台</span>
              </template>
            </el-statistic>
          </el-col>
          <el-col :span="8">
            <el-statistic title="失败" :value="importResultData.failed_count">
              <template #suffix>
                <span style="font-size: 14px; color: #909399;">台</span>
              </template>
            </el-statistic>
          </el-col>
          <el-col :span="8" v-if="importResultData.init_root_success !== undefined">
            <el-statistic title="root初始化" :value="importResultData.init_root_success">
              <template #suffix>
                <span style="font-size: 14px; color: #909399;">台</span>
              </template>
            </el-statistic>
          </el-col>
        </el-row>

        <!-- 成功列表 - 如果有成功的主机，显示提示信息 -->
        <el-alert
          v-if="importResultData.success_count > 0"
          type="success"
          :closable="false"
          class="mb-3"
        >
          <template #title>
            <div style="display: flex; align-items: center;">
              <el-icon style="margin-right: 8px;"><CircleCheck /></el-icon>
              <span>成功导入 {{ importResultData.success_count }} 台服务器</span>
            </div>
          </template>
        </el-alert>

        <!-- 失败列表 -->
        <el-card v-if="importResultData.failed_list && importResultData.failed_list.length > 0" shadow="never">
          <template #header>
            <div style="display: flex; align-items: center;">
              <el-icon style="color: #f56c6c; margin-right: 8px;"><CircleClose /></el-icon>
              <span>失败列表 ({{ importResultData.failed_list.length }})</span>
            </div>
          </template>
          <el-table :data="importResultData.failed_list" border size="small" max-height="300">
            <el-table-column label="主机IP" prop="ip" width="150" align="center" />
            <el-table-column label="状态" width="100" align="center">
              <template #default>
                <el-tag type="danger" size="small">失败</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="错误信息" min-width="400">
              <template #default="{ row }">
                <el-tooltip :content="row.reason" placement="top" effect="dark">
                  <div style="
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    color: #f56c6c;
                    font-size: 12px;
                  ">
                    {{ row.reason }}
                  </div>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
      <template #footer>
        <el-button type="primary" @click="importResultDialogVisible = false">确定</el-button>
      </template>
    </el-dialog>

    <!-- 日志查看对话框 -->
    <el-dialog
      :title="`查看日志 - ${currentHost?.host_name}`"
      v-model="logDialogVisible"
      width="1000px"
      :close-on-click-modal="false"
    >
      <el-form :inline="true" class="mb-3">
        <el-form-item label="日志日期">
          <el-select v-model="selectedLogDate" placeholder="请选择日志日期" @change="handleLoadLog" style="width: 200px;">
            <el-option
              v-for="date in logDates"
              :key="date"
              :label="date"
              :value="date"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="显示行数">
          <el-input-number v-model="logTailLines" :min="50" :max="1000" :step="50" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Refresh" @click="handleLoadLog">刷新</el-button>
        </el-form-item>
      </el-form>
      <el-input
        v-model="logContent"
        type="textarea"
        :rows="20"
        readonly
        style="font-family: monospace; font-size: 12px;"
      />
      <template #footer>
        <el-button type="primary" @click="logDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Edit,
  Delete,
  Search,
  Refresh,
  Upload,
  Connection,
  Document,
  CaretRight,
  SwitchButton,
  RefreshRight,
  Key,
  CircleCheck,
  CircleClose,
  Loading,
  InfoFilled,
  ArrowDown
} from '@element-plus/icons-vue'
import {
  getServerHostList,
  addServerHost,
  updateServerHost,
  deleteServerHost,
  batchDeleteServerHosts,
  batchImportServerHosts,
  testConnection,
  batchTestConnection,
  initRootAccount,
  batchInitRootAccount,
  executeCommand,
  deployAgent,
  controlAgent,
  getAgentLog,
  getAgentLogDates,
  checkAgentStatus,
  uploadAgentFile
} from '@/api/server'

// 状态
const loading = ref(false)
const showSearch = ref(true)
const total = ref(0)
const hostList = ref([])
const selectedHosts = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const importDialogVisible = ref(false)
const deployDialogVisible = ref(false)
const deployLoading = ref(false)
const resultDialogVisible = ref(false)
const commandResults = ref([])
const logDialogVisible = ref(false)
const logDates = ref([])
const logContent = ref('')
const selectedLogDate = ref('')
const logTailLines = ref(100)
const currentHost = ref(null)
const commandText = ref('')
const commandExecuting = ref(false)
const importResultDialogVisible = ref(false)
const importResultData = ref(null)
const batchTestLoading = ref(false)
// 文件上传相关状态
const uploadLoading = ref(false)
const uploadProgress = ref(0)
const uploadFileList = ref([])
const uploadRef = ref(null)

// 查询参数
const queryParams = reactive({
  page_num: 1,
  page_size: 20,
  host_name: '',
  host_ip: '',
  connection_status: '',
  agent_status: '',
  deploy_status: ''
})

// 表单
const form = reactive({
  id: null,
  host_name: '',
  host_ip: '',
  ssh_port: 22,
  ssh_username: 'root',
  ssh_password: '',
  agent_path: '/home/project/',
  remark: ''
})

// 导入表单
const importForm = reactive({
  ip_list_text: '',
  name_prefix: 'Server',
  ssh_port: 22,
  ssh_username: 'ubuntu',
  ssh_password: '',
  agent_path: '/home/project/',
  auto_init_root: true  // 默认启用自动初始化root
})

// 部署表单
const deployForm = reactive({
  agent_file_path: '/tmp/agent.tar.gz'
})

// 表单验证规则
const rules = {
  host_name: [{ required: true, message: '请输入主机名称', trigger: 'blur' }],
  host_ip: [{ required: true, message: '请输入主机IP', trigger: 'blur' }],
  ssh_port: [{ required: true, message: '请输入SSH端口', trigger: 'blur' }],
  ssh_username: [{ required: true, message: '请输入SSH用户名', trigger: 'blur' }],
  ssh_password: [{ required: true, message: '请输入SSH密码', trigger: 'blur' }]
}

const importRules = {
  ip_list_text: [{ required: true, message: '请输入IP地址列表', trigger: 'blur' }],
  ssh_username: [{ required: true, message: '请输入SSH用户名', trigger: 'blur' }],
  ssh_password: [{ required: true, message: '请输入SSH密码', trigger: 'blur' }]
}

const deployRules = {
  agent_file_path: [{ required: true, message: '请输入Agent安装包路径', trigger: 'blur' }]
}

// Refs
const queryRef = ref()
const formRef = ref()
const importFormRef = ref()
const deployFormRef = ref()

// 生命周期
onMounted(() => {
  getList()
})

// 获取列表
async function getList() {
  loading.value = true
  try {
    const res = await getServerHostList(queryParams)
    hostList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    ElMessage.error('获取主机列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
function handleQuery() {
  queryParams.page_num = 1
  getList()
}

// 重置搜索
function resetQuery() {
  queryRef.value?.resetFields()
  handleQuery()
}

// 选择变化
function handleSelectionChange(selection) {
  selectedHosts.value = selection
}

// 新增
function handleAdd() {
  resetForm()
  dialogTitle.value = '添加主机'
  dialogVisible.value = true
}

// 编辑
function handleUpdate(row) {
  resetForm()
  Object.assign(form, row)
  dialogTitle.value = '编辑主机'
  dialogVisible.value = true
}

// 删除
async function handleDelete(row) {
  try {
    await ElMessageBox.confirm('确认删除该主机吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteServerHost(row.id)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
async function handleBatchDelete() {
  try {
    await ElMessageBox.confirm(`确认删除选中的 ${selectedHosts.value.length} 台主机吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const ids = selectedHosts.value.map(item => item.id)
    await batchDeleteServerHosts(ids)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
async function submitForm() {
  try {
    await formRef.value.validate()
    if (form.id) {
      await updateServerHost(form.id, form)
      ElMessage.success('更新成功')
    } else {
      await addServerHost(form)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

// 重置表单
function resetForm() {
  form.id = null
  form.host_name = ''
  form.host_ip = ''
  form.ssh_port = 22
  form.ssh_username = 'root'
  form.ssh_password = ''
  form.agent_path = '/home/project/'
  form.remark = ''
  formRef.value?.resetFields()
}

// 批量导入
function handleImport() {
  importForm.ip_list_text = ''
  importForm.name_prefix = 'Server'
  importForm.ssh_port = 22
  importForm.ssh_username = 'ubuntu'
  importForm.ssh_password = ''
  importForm.agent_path = '/home/project/'
  importForm.auto_init_root = true
  importDialogVisible.value = true
}

// 文件上传
function handleFileChange(file) {
  const reader = new FileReader()
  reader.onload = (e) => {
    importForm.ip_list_text = e.target.result
  }
  reader.readAsText(file.raw)
}

// 提交导入
async function submitImport() {
  try {
    await importFormRef.value.validate()
    
    // 解析IP列表
    const ipList = importForm.ip_list_text
      .split('\n')
      .map(ip => ip.trim())
      .filter(ip => ip)
    
    if (ipList.length === 0) {
      ElMessage.warning('请输入至少一个IP地址')
      return
    }
    
    const data = {
      ip_list: ipList,
      name_prefix: importForm.name_prefix,
      ssh_port: importForm.ssh_port,
      ssh_username: importForm.ssh_username,
      ssh_password: importForm.ssh_password,
      agent_path: importForm.agent_path
    }
    
    const loading = ElMessage({
      message: importForm.auto_init_root ? '正在导入并初始化root账号，请稍候...' : '正在导入，请稍候...',
      type: 'success',
      duration: 0
    })
    
    try {
      const res = await batchImportServerHosts(data, importForm.auto_init_root)
      
      // 显示结果对话框
      if (res.data) {
        importResultData.value = res.data
        importResultDialogVisible.value = true
        
        // 根据结果显示不同的提示
        if (res.data.success_count > 0 && res.data.failed_count === 0) {
          ElMessage.success(`导入成功！成功导入 ${res.data.success_count} 台服务器`)
        } else if (res.data.success_count > 0 && res.data.failed_count > 0) {
          ElMessage.warning(`部分导入成功：成功 ${res.data.success_count} 台，失败 ${res.data.failed_count} 台`)
        } else {
          ElMessage.error(`导入失败：${res.data.failed_count} 台服务器导入失败`)
        }
      } else {
        ElMessage.success(res.msg || '导入成功')
      }
      
      importDialogVisible.value = false
      getList()
    } catch (error) {
      // 错误信息已经在request.js中显示，这里只需要记录日志
      console.error('导入失败:', error)
    } finally {
      // 确保在任何情况下都关闭loading
      loading.close()
    }
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

// 初始化root账号
async function handleInitRoot(row) {
  try {
    await ElMessageBox.confirm(
      `确认将主机 ${row.host_name} (${row.host_ip}) 的root密码设置为当前账号密码，并切换到root登录吗？`,
      '初始化root账号',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const loading = ElMessage({
      message: '正在初始化root账号，请稍候...',
      type: 'success',
      duration: 0
    })
    
    const res = await initRootAccount(row.id)
    loading.close()
    
    if (res.code === 200) {
      ElMessage.success(res.msg || 'root账号初始化成功')
      getList()
    } else {
      ElMessage.error(res.msg || '初始化失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('初始化失败')
    }
  }
}

// 批量初始化root账号
async function handleBatchInitRoot() {
  if (selectedHosts.value.length === 0) {
    ElMessage.warning('请先选择要切换的主机')
    return
  }
  
  // 过滤出非root的主机
  const nonRootHosts = selectedHosts.value.filter(h => h.ssh_username !== 'root')
  
  if (nonRootHosts.length === 0) {
    ElMessage.warning('所选主机都已经是root账号，无需切换')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确认将 ${nonRootHosts.length} 台主机的root密码设置为当前账号密码，并切换到root登录吗？\n\n主机列表：\n${nonRootHosts.map(h => `• ${h.host_name} (${h.host_ip})`).join('\n')}`,
      '批量初始化root账号',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false
      }
    )
    
    const loading = ElMessage({
      message: `正在批量初始化root账号（${nonRootHosts.length}台），请稍候...`,
      type: 'success',
      duration: 0
    })
    
    const hostIds = nonRootHosts.map(h => h.id)
    const res = await batchInitRootAccount(hostIds)
    loading.close()
    
    if (res.code === 200) {
      ElMessage.success(res.msg || '批量初始化完成')
      getList()
    } else {
      ElMessage.error(res.msg || '批量初始化失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量初始化失败')
    }
  }
}

// 处理下拉菜单命令
function handleDropdownCommand(command, row) {
  switch (command) {
    case 'testConnection':
      handleTestConnection(row)
      break
    case 'initRoot':
      handleInitRoot(row)
      break
    case 'viewLog':
      handleViewLog(row)
      break
    case 'start':
    case 'restart':
    case 'stop':
      handleControlAgent(row, command)
      break
  }
}

// 测试连接
async function handleTestConnection(row) {
  const loading = ElMessage({
    message: '正在测试连接...',
    type: 'success',
    duration: 0
  })
  
  try {
    const res = await testConnection(row.id)
    loading.close()
    if (res.data.status === 'success') {
      const connectionType = res.data.connection_type || '外网'
      const typeIcon = connectionType === '内网' ? '🏠' : '🌐'
      ElMessage.success(`${res.data.message}，耗时 ${res.data.duration}ms ${typeIcon}`)
      // 更新延迟信息和连接类型
      const host = hostList.value.find(h => h.id === row.id)
      if (host) {
        host.latency = res.data.duration
        host.connection_status = 'connected'
        host.connection_type = connectionType
        // 更新内网IP
        if (res.data.internal_ip) {
          host.internal_ip = res.data.internal_ip
        }
      }
      getList()
    } else {
      ElMessage.error(`连接失败：${res.data.message}`)
      // 更新延迟信息
      const host = hostList.value.find(h => h.id === row.id)
      if (host) {
        host.latency = res.data.duration || null
        host.connection_status = 'error'
      }
    }
  } catch (error) {
    loading.close()
    ElMessage.error('连接测试失败')
  }
}

// 批量测试连接
async function handleBatchTestConnection() {
  if (selectedHosts.value.length === 0) {
    ElMessage.warning('请选择要测试的主机')
    return
  }
  
  batchTestLoading.value = true
  const loading = ElMessage({
    message: `正在批量测试 ${selectedHosts.value.length} 台主机连接...`,
    type: 'success',
    duration: 0
  })
  
  try {
    const hostIds = selectedHosts.value.map(h => h.id)
    const res = await batchTestConnection(hostIds)
    loading.close()
    batchTestLoading.value = false
    
    if (res.code === 200 && res.data && res.data.results) {
      // 更新延迟信息、连接类型和内网IP
      let detectedInternalIpCount = 0
      res.data.results.forEach(result => {
        const host = hostList.value.find(h => h.id === result.host_id)
        if (host) {
          host.latency = result.duration
          host.connection_status = result.status === 'success' ? 'connected' : 'error'
          host.connection_type = result.connection_type || '外网'  // 保存连接类型
          // 如果检测到内网IP，更新显示
          if (result.internal_ip) {
            host.internal_ip = result.internal_ip
            detectedInternalIpCount++
          }
        }
      })
      
      const successCount = res.data.results.filter(r => r.status === 'success').length
      const failedCount = res.data.results.length - successCount
      
      let message = ''
      if (successCount > 0 && failedCount === 0) {
        message = `全部连接成功！共 ${successCount} 台`
      } else if (successCount > 0) {
        message = `部分连接成功：成功 ${successCount} 台，失败 ${failedCount} 台`
      } else {
        message = `全部连接失败：共 ${failedCount} 台`
      }
      
      if (detectedInternalIpCount > 0) {
        message += `，检测到 ${detectedInternalIpCount} 台内网IP`
      }
      
      if (successCount > 0 && failedCount === 0) {
        ElMessage.success(message)
      } else if (successCount > 0) {
        ElMessage.warning(message)
      } else {
        ElMessage.error(message)
      }
      
      // 刷新列表以更新连接状态和内网IP
      getList()
    } else {
      ElMessage.error(res.msg || '批量测试连接失败')
    }
  } catch (error) {
    loading.close()
    batchTestLoading.value = false
    ElMessage.error('批量测试连接失败')
  }
}

// 执行命令
async function handleExecuteCommand() {
  if (!commandText.value) {
    ElMessage.warning('请输入要执行的命令')
    return
  }
  
  if (selectedHosts.value.length === 0) {
    ElMessage.warning('请选择要执行命令的主机')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确认在 ${selectedHosts.value.length} 台主机上执行命令: ${commandText.value}？`,
      '执行确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
  } catch (error) {
    // 用户点击取消，直接返回
    if (error === 'cancel') {
      return
    }
  }
  
  commandExecuting.value = true
  let loading = null
  try {
    loading = ElMessage({
      message: '正在执行命令，请稍候...',
      type: 'success',
      duration: 0
    })
    
    const data = {
      host_ids: selectedHosts.value.map(item => item.id),
      command: commandText.value,
      command_type: 'custom'
    }
    
    const res = await executeCommand(data)
    
    // 确保关闭loading消息
    if (loading) {
      loading.close()
      loading = null
    }
    
    commandResults.value = res.data.results || []
    resultDialogVisible.value = true
    ElMessage.success(res.msg || '执行完成')
    getList()
  } catch (error) {
    // 确保关闭loading消息
    if (loading) {
      loading.close()
      loading = null
    }
    
    ElMessage.error('命令执行失败')
  } finally {
    commandExecuting.value = false
    // 双重保险：确保loading被关闭
    if (loading) {
      loading.close()
    }
  }
}

// 批量部署Agent
function handleBatchDeploy() {
  // 重置上传状态
  uploadLoading.value = false
  uploadProgress.value = 0
  uploadFileList.value = []
  deployForm.agent_file_path = ''
  deployDialogVisible.value = true
}

// 取消部署（清理上传状态）
function handleCancelDeploy() {
  deployDialogVisible.value = false
  uploadLoading.value = false
  uploadProgress.value = 0
  uploadFileList.value = []
  deployForm.agent_file_path = ''
}

// 上传前校验
function beforeUploadAgent(file) {
  const isValidFormat = file.name.endsWith('.tar.gz')
  const isLt500M = file.size / 1024 / 1024 < 500
  
  if (!isValidFormat) {
    ElMessage.error('只能上传 .tar.gz 格式的文件！')
    return false
  }
  if (!isLt500M) {
    ElMessage.error('文件大小不能超过 500MB！')
    return false
  }
  return true
}

// 文件超出数量限制
function handleExceed() {
  ElMessage.warning('一次只能上传一个文件，请先删除已选文件')
}

// 自定义上传处理
async function handleUploadAgent(options) {
  const { file } = options
  
  uploadLoading.value = true
  uploadProgress.value = 0
  
  try {
    // 调用上传API，传入进度回调
    const res = await uploadAgentFile(file, (progressEvent) => {
      if (progressEvent.total) {
        uploadProgress.value = Math.round((progressEvent.loaded * 100) / progressEvent.total)
      }
    })
    
    if (res.code === 200 && res.data) {
      ElMessage.success('上传成功！')
      
      // 自动填充下载URL
      deployForm.agent_file_path = res.data.download_url
      
      // 更新文件列表显示
      uploadFileList.value = [{
        name: res.data.file_name,
        url: res.data.download_url,
        status: 'success'
      }]
      
      // 显示上传结果信息
      ElMessage({
        message: `文件已上传到控制端，Token有效期：${Math.round(res.data.expires_in / 3600)}小时`,
        type: 'info',
        duration: 5000
      })
    } else {
      throw new Error(res.msg || '上传失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '文件上传失败')
    uploadFileList.value = []
    deployForm.agent_file_path = ''
  } finally {
    uploadLoading.value = false
    // 保持进度条在100%显示一会儿
    setTimeout(() => {
      uploadProgress.value = 0
    }, 2000)
  }
}

// 提交部署
async function submitDeploy() {
  try {
    await deployFormRef.value.validate()
    
    deployLoading.value = true
    const data = {
      host_ids: selectedHosts.value.map(item => item.id),
      agent_file_path: deployForm.agent_file_path
    }
    
    const res = await deployAgent(data)
    
    commandResults.value = res.data.results || []
    deployDialogVisible.value = false
    resultDialogVisible.value = true
    ElMessage.success(res.msg || '部署完成')
    getList()
  } catch (error) {
    ElMessage.error('部署失败')
  } finally {
    deployLoading.value = false
  }
}

// 批量获取Agent状态
async function handleBatchGetStatus() {
  if (selectedHosts.value.length === 0) {
    ElMessage.warning('请选择要获取状态的主机')
    return
  }
  
  const loading = ElMessage({
    message: `正在获取 ${selectedHosts.value.length} 台主机的Agent状态...`,
    type: 'success',
    duration: 0
  })
  
  try {
    const data = {
      host_ids: selectedHosts.value.map(item => item.id),
      action: 'status'
    }
    
    const res = await controlAgent(data)
    loading.close()
    
    if (res.code === 200) {
      commandResults.value = res.data.results || []
      resultDialogVisible.value = true
      ElMessage.success(res.msg || '获取状态完成')
      // 刷新列表以更新状态
      getList()
    } else {
      ElMessage.error(res.msg || '获取状态失败')
    }
  } catch (error) {
    loading.close()
    ElMessage.error('获取状态失败')
  }
}

// 批量控制Agent
async function handleBatchControlAgent(action) {
  const actionNames = {
    start: '启动',
    stop: '停止',
    restart: '重启'
  }
  
  try {
    await ElMessageBox.confirm(
      `确认${actionNames[action]} ${selectedHosts.value.length} 台主机的Agent服务吗？`,
      '操作确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const loading = ElMessage({
      message: `正在${actionNames[action]}Agent服务，请稍候...`,
      type: 'success',
      duration: 0
    })
    
    const data = {
      host_ids: selectedHosts.value.map(item => item.id),
      action: action
    }
    
    const res = await controlAgent(data)
    loading.close()
    
    commandResults.value = res.data.results || []
    resultDialogVisible.value = true
    ElMessage.success(res.msg || '操作完成')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}


// 控制单个Agent服务（启动/重启/停止）
async function handleControlAgent(row, action) {
  if (row.deploy_status !== 'deployed') {
    ElMessage.warning('请先部署Agent')
    return
  }
  
  const actionNames = {
    'start': '启动',
    'stop': '停止',
    'restart': '重启'
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要${actionNames[action]} ${row.host_name} 的Agent服务吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    row.controlLoading = true
    const loading = ElMessage({
      message: `正在${actionNames[action]}Agent服务，请稍候...`,
      type: 'success',
      duration: 0
    })
    
    const data = {
      host_ids: [row.id],
      action: action
    }
    
    const res = await controlAgent(data)
    loading.close()
    
    if (res.code === 200 && res.data.results && res.data.results.length > 0) {
      const result = res.data.results[0]
      if (result.status === 'success') {
        ElMessage.success(`${actionNames[action]}成功`)
        // 更新列表中的状态
        getList()
      } else {
        ElMessage.error(result.error || `${actionNames[action]}失败`)
      }
    } else {
      ElMessage.error(res.msg || `${actionNames[action]}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`${actionNames[action]}失败`)
    }
  } finally {
    row.controlLoading = false
  }
}

// 查看日志
async function handleViewLog(row) {
  currentHost.value = row
  logDialogVisible.value = true
  
  // 加载日志日期列表
  try {
    const res = await getAgentLogDates(row.id)
    logDates.value = res.data.dates || []
    if (logDates.value.length > 0) {
      selectedLogDate.value = logDates.value[0]
      handleLoadLog()
    }
  } catch (error) {
    ElMessage.error('获取日志日期列表失败')
  }
}

// 加载日志
async function handleLoadLog() {
  if (!selectedLogDate.value) {
    ElMessage.warning('请选择日志日期')
    return
  }
  
  const loading = ElMessage({
    message: '正在加载日志...',
    type: 'success',
    duration: 0
  })
  
  try {
    const data = {
      host_id: currentHost.value.id,
      log_date: selectedLogDate.value,
      tail_lines: logTailLines.value
    }
    const res = await getAgentLog(data)
    loading.close()
    logContent.value = res.data.log_content || '暂无日志内容'
  } catch (error) {
    loading.close()
    ElMessage.error('加载日志失败')
  }
}

/**
 * 自然排序函数（用于主机名排序）
 * 实现 agent-1, agent-2, ..., agent-10, agent-11 的排序
 * 而不是字母排序 agent-1, agent-11, agent-2, ...
 */
function naturalSortByHostName(a, b) {
  const aName = a.host_name || ''
  const bName = b.host_name || ''
  
  // 如果有空值，将空值排到最后
  if (!aName && !bName) return 0
  if (!aName) return 1
  if (!bName) return -1
  
  // 使用正则表达式分割字符串和数字
  const regex = /(\d+)|(\D+)/g
  const aParts = aName.match(regex) || []
  const bParts = bName.match(regex) || []
  
  // 逐部分比较
  const minLength = Math.min(aParts.length, bParts.length)
  for (let i = 0; i < minLength; i++) {
    const aPart = aParts[i]
    const bPart = bParts[i]
    
    // 检查是否都是数字
    const aIsNum = /^\d+$/.test(aPart)
    const bIsNum = /^\d+$/.test(bPart)
    
    if (aIsNum && bIsNum) {
      // 两者都是数字，按数值比较
      const diff = parseInt(aPart, 10) - parseInt(bPart, 10)
      if (diff !== 0) return diff
    } else {
      // 至少有一个不是数字，按字符串比较
      const diff = aPart.localeCompare(bPart)
      if (diff !== 0) return diff
    }
  }
  
  // 如果前面部分都相同，比较长度
  return aParts.length - bParts.length
}
</script>

<style scoped>
.command-card {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mr-2 {
  margin-right: 8px;
}

.mb-2 {
  margin-bottom: 8px;
}

.mb-3 {
  margin-bottom: 12px;
}

.mb-4 {
  margin-bottom: 16px;
}

/* 上传组件样式优化 */
.upload-demo {
  width: 100%;
}

.upload-demo :deep(.el-upload-list) {
  margin-top: 12px;
}

.upload-demo :deep(.el-upload-list__item) {
  transition: all 0.3s;
  border-radius: 4px;
}

.upload-demo :deep(.el-upload-list__item:hover) {
  background-color: #f5f7fa;
}

/* 进度条样式 */
:deep(.el-progress__text) {
  font-size: 14px !important;
  font-weight: 500;
}

/* 分割线样式 */
:deep(.el-divider__text) {
  background-color: #fff;
  color: #909399;
  font-size: 12px;
}
</style>

